package com.sfj.config.property;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * @author kaka
 * @Date 2025/5/1
 */
public class ResourceFactory extends DefaultPropertySourceFactory {

    public static final String SOURCE_BEAN_NAME = "kaka";

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        ClassPathResource resourcePath = (ClassPathResource) encodedResource.getResource();
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources(ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath.getPath()+"*.yml");
        Properties properties = new Properties();
        for(Resource resource : resources) {
            EncodedResource encoded = new EncodedResource(resource, "UTF-8");
            Properties propertiesTmp = addProperty(encoded);
            if (propertiesTmp == null) {
                continue;
            }
            properties.putAll(propertiesTmp);
        }
        return new PropertiesPropertySource(SOURCE_BEAN_NAME, properties);
    }

    public Properties addProperty(EncodedResource resource) {
        String sourceName = resource.getResource().getFilename();
        assert sourceName != null;
        if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            Properties properties = factory.getObject();
            assert properties != null;
            return properties;
        }
        return null;
    }
}
